import {
	WSS_SERVER_URL
} from "@/config/socket.js"
import {
	getGoldPrice
} from "@/api/new_api.js"
import store from "../store"
class webSocketClass {
	constructor(url, time = 60) {
		let wsUrl = url || WSS_SERVER_URL
		this.url = wsUrl
		this.data = null
		this.isCreate = false // WebSocket 是否创建成功
		this.isConnect = false // 是否已经连接
		this.isInitiative = false // 是否主动断开
		this.timeoutNumber = time // 心跳检测间隔
		this.heartbeatTimer = null // 心跳检测定时器
		this.reconnectTimer = null // 断线重连定时器
		this.socketExamples = null // websocket实例
		this.againTime = 1 // 重连等待时间(单位秒)&&金价刷新时间
		this.timeOut = false // 是否连接超时,超时后轮询请求金价接口
		this.timerGold = null //手动获取金价计时器
	}

	// 初始化websocket连接
	initSocket() {
		return
		const _this = this
		try {
			this.socketExamples = uni.connectSocket({
				url: _this.url,
				success: (res) => {
					_this.isCreate = true
				},
				fail: (rej) => {
					_this.isCreate = false
				}
			})
			this.createSocket()
		} catch (error) {
			console.log(error, "web错误----------");
			//TODO handle the exception
		}

	}

	// 创建websocket连接
	createSocket() {
		if (this.isCreate) {

			// 监听 WebSocket 连接打开事件
			try {
				this.socketExamples.onOpen(() => {
					console.log('WebSocket 连接成功')
					this.isConnect = true
					clearInterval(this.heartbeatTimer)
					clearTimeout(this.reconnectTimer)

					// 打开心跳检测
					this.heartbeatCheck()
				})
				// 监听 WebSocket 接受到服务器的消息事件
				this.socketExamples.onMessage((res) => {
					uni.$emit('message', res)
					this.webToPrice(res)
				})
				// 监听 WebSocket 连接关闭事件（websocket多次尝试连接后会连接超时，此时不会触发onClose回调）
				this.socketExamples.onClose((res) => {
					console.log('WebSocket 关闭了')
					this.isConnect = false
					this.reconnect()
					uni.$emit('webClose')
				})
				// 监听 WebSocket 错误事件
				this.socketExamples.onError((res) => {
					console.log('WebSocket 出错了')
					this.timeOut = res.errMsg.includes('Timed') || res.errMsg.includes('Invalid HTTP')
					uni.$emit('webError', this.timeOut)
				})
			} catch (error) {
				console.warn(error)
			}
		} else {
			console.warn('WebSocket 初始化失败!')
		}
	}
	// 通过websocket获取实时金价
	webToPrice() {
		uni.$on('message', (res) => {
			const rdata = res.data
			const data = typeof rdata === "string" ? JSON.parse(rdata) : rdata
			store.commit('setRealTimePriceData', data.price)
		})
	}
	// websocket连接超时后会在需要金价的页面轮询
	intervalGetPrice(delay = 2000) {
		if (this.timerGold) this.clearIntervalGetPice()
		this.httpsToPrice()
		this.timerGold = setInterval(() => {
			this.httpsToPrice()
		}, delay)
		console.log("应该设置了啊------", this.timerGold);
		// store.commit('setTimerGoldInterval', timerGold)
	}
	clearIntervalGetPice() {

		clearInterval(this.timerGold)
	}
	// 获取调用接口获取实时金价（websocket关闭尝试重连期间会主动调起）
	httpsToPrice() {
		console.log("调用金价接口");
		try {
			console.timeEnd()
			getGoldPrice().then((res) => {
				const data = res.data
				store.commit('setRealTimePriceData', data)
			})

		} catch (error) {
			console.log(error, "错误");
			//TODO handle the exception
		}


	}
	// 发送消息
	sendMsg(value) {
		const param = JSON.stringify(value)
		return new Promise((resolve, reject) => {
			this.socketExamples.send({
				data: param,
				success() {
					console.log('消息发送成功')
					resolve(true)
				},
				fail(error) {
					console.log('消息发送失败')
					reject(error)
				}
			})
		})
	}

	// 开启心跳检测
	heartbeatCheck() {
		this.data = {
			state: 1,
			method: 'heartbeat'
		}
		this.heartbeatTimer = setInterval(() => {
			this.sendMsg(this.data)
		}, this.timeoutNumber * 1000)
	}

	// 重新连接
	reconnect() {
		console.log("重连websocket");
		// 停止发送心跳
		clearTimeout(this.reconnectTimer)
		clearInterval(this.heartbeatTimer)
		// 如果不是人为关闭的话，进行重连
		console.log(this.isInitiative, "是否人为关闭");
		if (!this.isInitiative) {
			this.reconnectTimer = setTimeout(() => {
				this.initSocket()
			}, this.againTime * 1000)
		}
	}
	setIsInitiativeFalse() {
		this.isInitiative = false
	}
	setIsInitiativeTrue() {
		this.isInitiative = true
	}
	// 关闭 WebSocket 连接
	closeSocket(reason = '关闭') {
		const _this = this
		this.socketExamples.close({
			reason,
			success() {
				_this.data = null
				_this.isCreate = false
				_this.isConnect = false
				_this.isInitiative = true
				_this.socketExamples = null
				clearInterval(_this.heartbeatTimer)
				clearTimeout(_this.reconnectTimer)
				console.log('关闭 WebSocket 成功')
			},
			fail(err) {}
		})
	}
}

export default webSocketClass